package com.nineclock.message.Service.impl;

import cn.hutool.core.util.StrUtil;
import com.nineclock.message.JPushManager;
import com.nineclock.message.Service.MessageService;
import com.nineclock.message.dto.NcMessageDTO;
import com.nineclock.message.pojo.NcMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;


import java.util.List;


@Service
public class MessageServiceImpl implements MessageService {
    @Autowired
    private JPushManager jPushManager;
    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public Boolean pushSingleMessage(NcMessage message) throws Exception {
        //1. 保存推送消息
        mongoTemplate.save(message);
        //2. 推送消息
        return jPushManager.sendNotificationByAlias(message.getTitle(), message.getContent(), message.getTargets(), null);
    }

    /**
     * 获取推送历史记录
     * @return
     */
    @Override
    public List<NcMessage> findMessageRecord(NcMessageDTO messageDTO) {
        Query query=new Query();
        if (messageDTO == null) {
            messageDTO=new NcMessageDTO();
        }

        if (StrUtil.isNotEmpty(messageDTO.getId())){
            query.addCriteria(Criteria.where("_id").is(messageDTO.getId()));

        }
        if (StrUtil.isNotEmpty(messageDTO.getType())){
            query.addCriteria(Criteria.where("messageType").is(messageDTO.getType()));
        }
        if (messageDTO.getUserId()!=null){
            query.addCriteria(Criteria.where("applyUserId").is(messageDTO.getUserId()));
        }
        if (messageDTO.getTargetId()!=null){
            query.addCriteria(Criteria.where("approveUserId").is(messageDTO.getTargetId()));
        }
        //排序, 根据审核状态升序排序（必须排序，否则会不显示）
        query.with(Sort.by(Sort.Direction.ASC,"approveStatue"));

        List<NcMessage> ncMessages=mongoTemplate.find(query,NcMessage.class);
        return ncMessages;
    }

    @Override
    public void updateMessageWithApproved(String msgId) {


        Query query = new Query();
        query.addCriteria(Criteria.where("_id").is(msgId));

        Update update = new Update();
        update.set("useStatus",1);
        update.set("approveStatue",1);

        mongoTemplate.updateFirst(query, update, NcMessage.class);
    }
}    